<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\housing;

use think\facade\Db;
use app\common\repositories\BaseRepository;
use app\common\dao\housing\HousingResourceDao;
use app\common\repositories\housing\HousingPictureRepository;
use app\common\repositories\housing\HousingFacilityRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
use app\common\repositories\housing\HousingResourceLabelRepository;

/**
 * Class HousingResourceRepository
 *
 * @mixin HousingResourceDao
 */
class HousingResourceRepository extends BaseRepository
{

    public function __construct(HousingResourceDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->order('id', 'desc')
            ->select();
        foreach ($list as $k => $v) {
            if ($v['rent_type'] == 1) {
                $list[$k]['room_rent'] = $v['rent_price'] . ' ¥/m²/天';
            } else if ($v['rent_type'] == 2) {
                $list[$k]['room_rent'] = $v['rent_price'] . ' ¥/月';
            }
        }
        return compact('count', 'list');
    }

    public function getApiList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->append(['picture', 'label_list'])
            ->field('id,housing_title,room_size,rent_price,rent_type,is_reg,edit_time')
            ->order('top_time', 'desc')
            ->order('edit_time', 'desc')
            ->select();
        foreach ($list as $k => $v) {
            if ($v['rent_type'] == 1) {
                $list[$k]['room_rent'] = $v['rent_price'] . ' ¥/m²/天';
            } else if ($v['rent_type'] == 2) {
                $list[$k]['room_rent'] = $v['rent_price'] . ' ¥/月';
            }
            unset($v['rent_price']);
            unset($v['rent_type']);
        }
        return compact('count', 'list');
    }


    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        $picture = [];
        if (isset($data['picture'])) {
            $picture = $data['picture'];
        }
        unset($data['picture']);
        return Db::transaction(function () use ($data, $propertyId, $userId, $picture) {
            $labelIds = $data['label_id'];
            unset($data['label_id']);

            $facilitData = [];
            if (isset($data['facilit'])) {
                $facilitData = $data['facilit'];
                unset($data['facilit']);
            }

            $data['is_show'] = 1;
            $data['add_uid'] = $userId;
            $data['property_id'] = $propertyId;
            $resInfo = $this->dao->create($data);
            if ($picture) {
                /** @var HousingPictureRepository $pictureRepository */
                $pictureRepository = app()->make(HousingPictureRepository::class);
                $pictureRepository->addPicture($resInfo['id'], $picture, 1);
            }
            if ($labelIds) {
                /** @var HousingResourceLabelRepository $labelRepository .php */
                $labelRepository = app()->make(HousingResourceLabelRepository::class);
                $insertData = [];
                foreach ($labelIds as $v) {
                    $insertData[] = [
                        'label_id' => $v,
                        'housing_id' => $resInfo['id'],
                        'property_id' => $resInfo['property_id'],
                    ];
                }
                $labelRepository->insertAll($insertData);
            }

            if ($facilitData) {
                /** @var HousingFacilityRepository $housingFacilityRepository */
                $housingFacilityRepository = app()->make(HousingFacilityRepository::class);
                $housingFacilityRepository->setFacility($resInfo['id'], $facilitData);
            }

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'HOUSING.RESOURCE.ADD', $data);
            event('housing.create', [
                'userId' => $userId,
                'resourceInfo' => $resInfo,
            ]);
            return $resInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        $picture = null;
        if (isset($data['picture'])) {
            $picture = (array)$data['picture'];
        }
        unset($data['picture']);
        return Db::transaction(function () use ($data, $info, $userId, $picture) {
            $labelIds = $data['label_id'];
            unset($data['label_id']);

            $facilitData = $data['facilit'];
            unset($data['facilit']);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'HOUSING.RESOURCE.EDIT', $data);

            /** @var HousingPictureRepository $pictureRepository */
            $pictureRepository = app()->make(HousingPictureRepository::class);
            $pictureRepository->removePicture($info['id']);
            if ($picture !== null) {
                $resB = $pictureRepository->addPicture($info['id'], $picture, 1);
            }

            /** @var HousingResourceLabelRepository $labelRepository .php */
            $labelRepository = app()->make(HousingResourceLabelRepository::class);
            $labelRepository->deleteByResourceId($info['id']);
            if ($labelIds) {
                $insertData = [];
                foreach ($labelIds as $v) {
                    $insertData[] = [
                        'label_id' => $v,
                        'housing_id' => $info['id'],
                        'property_id' => $info['property_id'],
                    ];
                }
                $resC = $labelRepository->insertAll($insertData);
            }

            /** @var HousingFacilityRepository $housingFacilityRepository */
            $housingFacilityRepository = app()->make(HousingFacilityRepository::class);
            $housingFacilityRepository->clearFacility($info['id']);
            if ($facilitData) {
                $housingFacilityRepository->setFacility($info['id'], $facilitData);
            }

            $res = $this->dao->update($info['id'], $data);
            event('housing.redact', [
                'userId' => $userId,
                'resourceInfo' => $info,
            ]);
            return ($res || $resB || $resC);
        });
    }

    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->where('id', $id)
            ->find();
        return $data;
    }

    /**
     *  房源详情
     * @param int $id
     * @return \app\common\model\BaseModel|array|mixed|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-12 16:13
     */
    public function getApiDetail(int $id)
    {
        $data = $this->dao->getSearch([])
            ->where('id', $id)
            ->where('is_show', 1)
            ->append(['picture', 'label_list', 'facility'])
            ->field('id,housing_title,cate_id,floor_total,floor_name,room_size,address,rent_price,rent_type,pay_num,bet_num,start_rent,free_rent,is_reg,remark')
            ->find();

        ## 租金金额
        if ($data['rent_price'] <= 0) {
            $data['room_rent'] = '租金面议';
        } else if ($data['rent_type'] == 1 && $data['rent_price'] > 0) {
            $data['room_rent'] = $data['rent_price'] . ' ¥/m²/天';
        } else if ($data['rent_type'] == 2 && $data['rent_price'] > 0) {
            $data['room_rent'] = $data['rent_price'] . ' ¥/月';
        }
        unset($data['rent_price']);
        unset($data['rent_type']);
        ## 付款方式
        $data['pay_type'] = ($data['bet_num'] ? ('押 ' . $data['bet_num'] . ' 月') : '') . ($data['pay_num'] ? (' 付 ' . $data['pay_num'] . ' 月') : '');
        unset($data['bet_num']);
        unset($data['pay_num']);
        ## 楼层信息
        $data['floor_name'] = ($data['floor_name'] ? ('第 ' . $data['floor_name'] . ' 层') : '') . ($data['floor_total'] ? (' 共 ' . $data['floor_total'] . ' 层') : '');
        unset($data['floor_total']);

        return $data;
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids], ['status', 'in', [1]]
        ], 'id,property_id,property_id,status,room_title');
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        return Db::transaction(function () use ($info, $userId) {
            event('housing.delete', [
                'userId' => $userId,
                'roomInfo' => $info,
            ]);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'HOUSING.RESOURCE.DEL', $info);
            $this->dao->delete($info['id']);

        });
    }


}